<?php
namespace App\Http\Controllers\Backend\User;

use App\Library\Tools\ExcelExport;
use App\Models\LoanApply;
use App\Models\RepayRecord;
use App\Models\RepaySummary;
use App\Models\User;
use App\Models\UserCertOcr;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller {
    //
    public function __construct() {
//        $this->middleware('auth:backend');
        $this->user = auth('backend')->user();
    }

    /**
     * 首页
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\GeneralException
     * @author luwei
     * @date 2019-01-13 11:12
     */
    public function index(Request $request) {
//        UserLoanRequest::test();
//        $this->getStatus();
        $status      = $request->get('status');
        $childStatus = $request->get('detail_status');
        $name        = $request->get('name');
        $pageSize  = $request->get('page_size',10);
        $data        = User::userList($status, $childStatus, $name,$pageSize);
        return resp($data);
    }

    /**
     * 搜索状态列表
     * @return mixed
     * @author luwei
     * @date 2019-01-11 11:40
     */
    public function statusList() {
        $fullStatus       = User::$FULL_STATUS;
        $fullStatusDetail = User::$FULL_STATUS_DETAIL;
        $info             = [];
        foreach ($fullStatus as $k => $v) {
            $tmp = [];
            foreach ($fullStatusDetail[$k] as $key=>$value){
                $tmp[] = [
                    'id' => $key,
                    'name' => $value
                ];
            }
            $info[] = [
                'status'   => [
                    'id' => $k,
                    'name' => $v
                ],
                'detail_status' => $tmp
            ];
        }
        return success($info);
    }

    /**
     * 新用户列表
     * @param Request $request
     * @return mixed
     * @author luwei
     * @date 2019-01-13 10:50
     */
    public function newUser(Request $request){
        $phone = $request->get('phone');
        $pageSize = $request->get('page_size',10);
        $info = User::newUser($phone,$pageSize);
        array_map(function($data){
            $data['status'] = '未提单';
        },$info['data']);
        return resp($info);
    }

    /**
     * 用户详情
     * @param Request $request
     * @param $userId
     * @return mixed
     * @author luwei
     * @date 2019-01-11 11:40
     * @throws \App\Exceptions\GeneralException
     */
    public function show(Request $request, $userId){
        $data = User::dealLoanDetail($userId);
        return resp($data);
    }

    /**
     * 用户列表导出
     * @param Request $request
     * @throws \App\Exceptions\GeneralException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @author luwei
     * @date 2019-01-17 14:29
     */
    public function export(Request $request){
        $status      = $request->get('status');
        $childStatus = $request->get('detail_status');
        $name        = $request->get('name');
        $data        = User::userListExport($status, $childStatus, $name);
        $header = ['借款状态','细分状态','借记次数','渠道来源','用户ID','姓名','手机号码','tradeID','身份证号码','申请时间'];
        $fields = ['status_text','detail_status_text','count','source','user_id','name','phone','trade_id','card_num','apply_time'];
        $ret = new ExcelExport($data,$header,$fields,'user.xlsx');
        $ret->export();
    }

    /**
     * 新用户列表导出
     * @param Request $request
     * @return mixed
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @author luwei
     * @date 2019-01-13 10:50
     */
    public function newExport(Request $request){
        $phone = $request->get('phone');
        $info = User::newUserExport($phone);
        foreach ($info as &$v){
            $v['status'] = '未提单';
        }
        $header = ['借款状态','渠道来源','用户ID','手机号码','微信授权','注册时间','最后登录时间'];
        $fields = ['status','source','user_id','phone_num','openid','register_time','login_time'];
        $ret = new ExcelExport($info,$header,$fields,'new_user.xlsx');
        $ret->export();
    }


    /**
     * 根据姓名、身份证、手机号查询用户id
     * @author cg
     * @param Request $request
     * @return mixed
     */
    public function userlistFilter(Request $request)
    {
        $name = $request->get('name', '');
        $num = $request->get('num','');
        $phone_num = $request->get('phone_num','');
        $returnArr = [];
        $applys_uid = [];
        $uids = [];
        $user_cert = new UserCertOcr();
        $user_cert->setConnection('backend');
        $loan_apply = new LoanApply();
        $loan_apply->setConnection('backend');
        if($name != '' || $num != ''){
            $user_certs = $user_cert
                ->when($name, function ($query) use ($name) {
                    return $query->where('name', $name);
                })
                ->when($num, function($query) use ($num) {
                    return $query->where('num', $num);
                });
            $uids = $user_certs->pluck('user_id')->toArray();
            $uids = array_unique($uids);
            $applys_uid = $loan_apply->whereIn('user_id', $uids)->where('loan_status', LoanApply::LOAN_STATUS_SUCCESS)->pluck('user_id')->toArray();
        }else if ($phone_num){
            $user = new User();
            $user->setConnection('backend');
            $users = $user->where('phone_num', $phone_num)->first();
            if(!empty($users)){
                $uids = [$users->id];
                $applys_uid = $loan_apply->whereIn('user_id', $uids)->where('loan_status', LoanApply::LOAN_STATUS_SUCCESS)->pluck('user_id')->toArray();
            }
        }
        foreach ($applys_uid as $uid){
            $tmp = [];
            if(in_array($uid, $uids)){
                $tmp['status'] = 2;
                $tmp['uid'] = $uid;
            }else{
                $tmp['status'] = 1;
                $tmp['uid'] = $uid;
            }
            array_push($returnArr, $tmp);
        }
        if(empty($applys_uid)){
            $tmp = [];
            foreach ($uids as $uid){
                $tmp['status'] = 1;
                $tmp['uid'] = $uid;
            }
            array_push($returnArr, $tmp);
        }
        return success($returnArr);
    }
}
